"ui";


const version = require('./version')
const storageKey = 'SH'

const versionFn = new version(storageKey)
const V = versionFn.get()

const storeDir = '/sdcard/goldFinger'

// const publicStore = 'https://gitee.com/wxhxxx_520/download-file/raw/master'
const enginesList = []
const threadsList = []
storage = storages.create(storageKey);
const Resolution = device.width + '*' + device.height

const date = + new Date() || versionFn.formatDate()
log('date', date)
console.setGlobalLogConfig({
  "file": storeDir + "/log/" + date + ".txt"
});


var proName = '金手指'

const uiPath = './src/ui/'
header = 'file://' + files.path('./res/logo.png')

// 脚本运行的 引擎环境
var initEngine



var updateStatus = false

// 检查更新
const threadCheck = () => threads.start(checkUpdate)
threadCheck()


const initconfig = {
  device: 'phone',
  title: '金手指',
  bg: setcolor(2),
  showLog: false,
  debugging: false,
  MODE: 2,
  alreadyMerge: false,
  // 功能配置
  todos: {
    // 合兽
    merge: false,
    // 通过石头升级
    mergeByStone: false,
    // 异变
    yibian: false,
    // 菜补
    caibu: false,

    // 微信还是浏览器
    weixin: false,
    qqBrower: false,

    buyAnimal: false,
    lucky: false,
    flyDan: false,


    // 家园++++++++++
    homePickEgg: false,
    jingWei: false,
    // 夺宝
    treasure: false,
    // 开福袋
    fudai: false,

    //开箱子
    openBox: true,
    // 抢红包
    catchMoney: true,
  },
  treasureConfig: {
    refreshByCard: false
  },
  openBoxConfig: {

  }

}

function init () {

  let existConfig = storage.get('config')
  if (existConfig) {

    // 合并对象
    return assignDeep(existConfig, initconfig)
  }
  return initconfig
}


const config = init()
console.log('config', config);

// 
const functionList = [
  'weixin',
  'qqBrower',
  'debugging',

  'merge',
  'mergeByStone',
  'yibian',
  'caibu',
  'buyAnimal',
  'lucky',
  'flyDan',
  // 家园
  'jingWei',
  'treasure',
  'homePickEgg',

  // 抢红包
  "catchMoney"
]

// config第一层
const configEdit = [
  'alreadyMerge'
]

setInterval(() => {
}, 1000)


var cellWidth = device.width / 4
var cellHeight = 100


creatUI()
autoFly = null
// 开始运行
ui.start.on('click', () => {

  if (!autoFly) {
    autoFly = engines.execScriptFile(uiPath + '自定义悬浮.js')
  }
  home()
  // enginesList.push(autoFly)
})


let firstStart = false
events.broadcast.on('script_start', () => {

  if (!firstStart) {
    firstStart = true
    scriptStart()
  }
})

events.broadcast.on('script_end', () => {
  log('main.js', '结束脚本')
  firstStart = false
  scriptEnd()
})

// 功能修改
ui.run(function () {
  let id = 'Mode' + config.MODE
  ui[id] && ui[id].attr('checked', true)

})
fnListener(
  ['Mode1', 'Mode2', 'Mode3'],
  (e, id) => {
    if (e) {
      this.config.MODE = id.replace(/Mode/, '')
    }
  })


function creatUI () {
  ui.layout(
    <drawer id="drawer">
      <vertical bg="{{config.bg}}">
        <appbar>
          <toolbar id="toolbar" w="*" bg="{{config.bg}}" h="auto" title="{{config.title}}"></toolbar>
          <tabs id="tabs" />
        </appbar>
        <viewpager id="viewpager" borderWidth="1">
          {/* 功能 */}
          <frame>
            <scroll>
              <vertical gravity="center_horizontal">
                <text gravity="center" w="*" h="50" textSize="20sp" text="合兽配置"></text>
                <horizontal h="{{cellHeight}}px" gravity="left">
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="merge" checked="{{config.todos.merge}}" text="合兽" />
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="mergeByStone" checked="{{config.todos.mergeByStone}}" text="石头升级" />
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="buyAnimal" checked="{{config.todos.buyAnimal}}" text="灵气买兽" />
                  {/* <input id="leval" inputType="number" hint="请输入野怪等级" text="{{deploy.leval}}" /> */}
                </horizontal>
                <horizontal h="{{cellHeight}}px" gravity="left">
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="yibian" checked="{{config.todos.yibian}}" text="异变" />
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="flyDan" checked="{{config.todos.flyDan}}" text="飞升凝丹" />
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="homePickEgg" checked="{{config.todos.homePickEgg}}" text="家园领蛋" />
                </horizontal>
                <horizontal h="{{cellHeight}}px" gravity="left">
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="alreadyMerge" checked="{{config.alreadyMerge}}" text="今天已经合兽?" />
                </horizontal>


                <text gravity="center" w="*" h="50" textSize="20sp" text="每日任务"></text>
                <horizontal h="{{cellHeight}}px" gravity="left">
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="lucky" checked="{{config.todos.lucky}}" text="幸运值" />
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="caibu" checked="{{config.todos.caibu}}" text="采补" />
                </horizontal>



                <text gravity="center" w="*" h="{{cellHeight}}px" textSize="20sp" text="家园配置"></text>
                <horizontal h="{{cellHeight}}px" gravity="left">
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="jingWei" checked="{{config.todos.jingWei}}" text="精卫助手" />
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="treasure" checked="{{config.todos.treasure}}" text="夺宝" />
                </horizontal>

                <horizontal h="auto" gravity="left">
                  <checkbox marginRight="20" id="refreshByCard" checked="{{config.treasureConfig.refreshByCard}}" text="刷新卡刷新" />

                </horizontal>


                <horizontal h="{{cellHeight}}px" gravity="left">
                  <checkbox w="{{cellWidth}}px" marginRight="20" id="catchMoney" checked="{{config.todos.catchMoney}}" text="抢红包" />
                </horizontal>

              </vertical>

            </scroll>
          </frame>
          {/* 配置 */}
          <frame>
            <scroll>
              <vertical gravity="center_horizontal">
                <Switch id="autoService" text="开启无障碍服务" checked="{{auto.service != null}}" textColor="red" padding="8 8 8 8" textSize="15sp" />
                <Switch id="debugging" text="调试" checked="{{config.debugging}}" textColor="red" padding="8 8 8 8" textSize="15sp" />
                <Switch id="consoleShow" text="控制台显隐" checked="{{config.showLog}}" textColor="blue" padding="8 8 8 8" textSize="15sp" />

                <text w="auto" h="50" gravity="center" color="#228B22" size="16" text="登录设置" />
                <radiogroup id="device" orientation="horizontal">
                  <radio margin="10 0 0 0" checked="{{config.todos.weixin}}" id="weixin" text="微信" />
                  <radio margin="10 0 0 0" checked="{{config.device.qqBrower}}" id="qqBrower" text="qq浏览器" />
                </radiogroup>

                <text w="auto" h="50" gravity="center" color="#228B22" size="16" text="运行速度" />
                <radiogroup id="ModeWrap" orientation="horizontal">
                  <radio margin="10 0 0 0" id="Mode1" text="fast" />
                  <radio margin="10 0 0 0" id="Mode2" checked="true" text="normal" />
                  <radio margin="10 0 0 0" id="Mode3" text="slow" />
                </radiogroup>

                <button id="start" style="Widget.AppCompat.Button.Colored" text="运行" />

              </vertical>
            </scroll>
          </frame>
          {/* 帮助 */}
          <frame>
            <scroll>
              <vertical>
                <horizontal>
                  <text text="设备分辨率:{{Resolution}}"></text>
                </horizontal>
              </vertical>
            </scroll>
          </frame>
        </viewpager>
      </vertical>
      <vertical layout_gravity="left" width="200" bg="{{config.bg}}" >
        <img src="{{header}}" w='100' h='100' radius="50" layout_gravity="center" />
        <scroll>
          <list id="menu">
            <button bg="{{setcolor(1)}}" margin="2" borderColor="#409eff" w="*" text="{{title}}"></button>
          </list>
        </scroll>
      </vertical>
    </drawer>
  )
}


function scriptStart () {

  toast('初始化')
  // enginesList.forEach(execution => {
  //   execution.getEngine().forceStop()
  // })

  // 保存配置到内存中
  storage.put('config', config)

  // 在新线程中运行
  initEngine = engines.execScriptFile('./init.js')
  // enginesList.push(initEngine)

}

function scriptEnd () {
  try {
    initEngine && initEngine.getEngine().forceStop()
    // threads.shutDownAll()

    enginesList.forEach(execution => {
      execution.getEngine().forceStop()
    })

    threadsList.forEach(th => {
      th.interrupt()
    })

  } catch (error) {
    log('error', error)
  }
}



function checkUpdate () {


  // let version = baseApi('version.json').body.json()
  // log('version', version)

  const newVersion = versionFn.baseApi('version.json').body.json()

  log('最新版本' + '-*'.repeat(10) + newVersion.version)

  const needUpdate = versionFn.isNeedToUpdateFile(newVersion.version)

  ui.run(() => {
    let str = proName + '(' + versionFn.get() + ')'
    ui.toolbar.attr('title', str)
  })


  if (needUpdate) {
    toastLog('检查到新版本准备更新')
    // 停止脚本
    scriptEnd()

    let { suc, isUpdateUi } = toUpdateFile(newVersion.updateList)

    if (suc) {
      versionFn.set(newVersion.version)
      updateStatus = true
      ui.run(() => {
        let str = proName + '(' + newVersion.version + ')'

        ui.toolbar.attr('title', str)
      })
    }


    if (isUpdateUi) {
      sleep(2000)
      toastLog('Entry file updated, restarting')
      ui.finish();
      engines.stopAll()
      exit()
    }


  } else {
    toastLog('当前已是新版本')
  }

}


// 更新文件
function toUpdateFile (updateList) {

  toastLog('更新中^=0=^……')

  let isUpdateUi = false
  let suc = true
  let genPath = engines.myEngine().cwd()
  try {

    updateList.forEach(item => {


      const { localPath, originPath, type, update } = item
      if (!update) return


      const toPutPath = engines.myEngine().cwd() + localPath

      // var sc = http.get(publicStore + originPath)
      var sc = versionFn.baseApi(originPath)

      if (sc.statusCode == 200) {

        if (localPath === '/main.js') {
          isUpdateUi = true
        }


        log('cwd', engines.myEngine().cwd())

        log('文件' + localPath + '更新成功from', originPath)
        var createDir = localPath.replace(/(\w|[\u4e00-\u9fa5])*(.js|.zip)$/, '')


        if (createDir != '/') {
          files.ensureDir(genPath + createDir)
        }
        const filePath = genPath + localPath
        log('filePath', filePath)
        files.writeBytes(filePath, sc.body.bytes())


        if (type === 'zip') {
          // if (!$files.exists(localPath)) {
          //   $files.create(localPath);
          // }

          log('$zip.open(filePath).isValidZipFile()', $zip.open(filePath).isValidZipFile())

          // let zipName = originPath.match(/(\w*.zip)$/g)[0]

          // 压缩后文件存放路径  /1080/1080.zip
          let encryptedZipFile = filePath || engines.myEngine().cwd() + '/img/1080/1080.zip'

          log('encryptedZipFile', encryptedZipFile)


          // let output = engines.myEngine().cwd() + createDir

          // log('output', output)


          $zip.unzip(encryptedZipFile, './img/1080');

          $files.remove(encryptedZipFile); // 删除同名文件

          log('解压成功')

        }

        // return true
      } else {
        console.error('文件' + localPath + "更新失败from" + originPath)
      }
    })
  } catch (error) {
    suc = false
    log('更新出错', error)
  }


  sleep(1000)
  toastLog('更新完成^=0=^……')

  return {
    suc: suc,
    isUpdateUi
  }
}



events.on("exit", function () {
  if (updateStatus) {
    app.launch("com.goldfinger")
  }
});


//设置滑动页面的标题
ui.viewpager.setTitles(['功能', '配置', '帮助'])
//让滑动页和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager)

ui.autoService.on('check', function (e) {
  if (e && !auto.service) {
    app.startActivity({
      action: "android.settings.ACCESSIBILITY_SETTINGS"
    });
  }
  if (!checked && auto.service) {
    auto.service.disableSelf();
  }
})
// // 控制台
ui.consoleShow.on('check', function (e) {
  config.showLog = e
})


// 功能修改
fnListener(
  functionList,
  (e, id) => {
    if (id === 'debugging') {
      config[id] = e
    } else {
      config.todos[id] = e
    }
    log('config', config)
  })

// 配置修改
fnListener(
  configEdit,
  (e, id) => {
    config[id] = e
    log('config', config)
  })

function fnListener (idList, callback) {
  idList.forEach((id, index) => {
    ui[id].on('check', (e) => callback(e, id))
  })
}



// 左侧菜单
leftMenu()
function leftMenu () {
  ui.menu.setDataSource([{ title: '关于' }, { title: '退出' }, { title: 'clear' }, { title: '检查更新' }]);
  ui.menu.on("item_click", item => {
    switch (item.title) {
      case "更新日志":
        // app.openUrl('www.baidu.com');
        break;
      case "检查更新":
        threadCheck()
        // threads.start(function () {
        // let titileAndVersion = ui.toolbar.getTitle();
        // let appNameAndVersionArray = titileAndVersion.split("v");
        // let appName = appNameAndVersionArray[0];
        // let appVersion = appNameAndVersionArray[1];
        // var url = rootUrl + "/app/WebService.asmx/CheckAppVersion";
        // var version = appVersion;
        // var res = http.post(url, { "appName": appName, "version": version });
        // var returnString = res.body.string();
        // let json = JSON.parse(returnString);
        // if (json.success == "true") {
        //   if (json.data.upgrade == "true") {
        //     app.openUrl(rootUrl + "/app/WebService.asmx/DownLoadWoolUIApk");
        //   } else {
        //     toast("已经是最新版");
        //   }
        // } else {
        //   toast("请求远端服务器出现异常！请稍后重试！");
        // }
        // });
        break;
      case "教程":
        app.openUrl("https://blog.csdn.net/zy0412326/article/details/104767602");
        break;
      case "关于":
        dialogs.build({
          title: "关于",
          positive: "确定",
          items: ["某些手机不能用的问题"]
        }).on("show", (dialog) => { }).show();
        break;
      case 'clear':
        storage.clear()
        break;
      case "退出":
        ui.finish();
        engines.stopAll()
        exit()
        break;
    }
  });
  //让工具栏左上角可以打开侧拉菜单
  ui.toolbar.setupWithDrawer(ui.drawer);
}
function setcolor (v) {
  arr = ['#409eff', '#FFEBCD', '#bbd8bf']
  return arr[v]
}


setTimeout(() => { }, 60 * 60 * 24 * 1000)

function isPlainObject (obj) {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

function assignDeep () {
  const args = Array.from(arguments);
  if (args.length < 2) return args[0];
  let result = args[0];
  args.shift();
  args.forEach(item => {
    if (isPlainObject(item)) {
      if (!isPlainObject(result)) result = {}
      for (let key in item) {
        if (result[key] && isPlainObject(item[key])) {
          result[key] = assignDeep(result[key], item[key])
        } else {
          if (!result[key] && !Object.is(result[key], false)) {
            result[key] = item[key]
          }
        }
      }
    }
    else if (item instanceof Array) {
      if (!(result instanceof Array)) result = []
      item.forEach((arrItem, arrIndex) => {
        if (isPlainObject(arrItem)) {
          result[arrIndex] = assignDeep(result[arrIndex])
        } else {
          result[arrIndex] = arrItem
        }
      })
    }
  })
  return result
}


